<?php
/**
 * PageLogic.php
 * phpstorm_company_name_str - phpstorm_company_product_name
 * ***************************************************************************************************************************
 * 版权声明: Copyright ©2019 phpstorm_company_name_str All rights reserved
 * 官方网站: phpstorm_company_product_url
 * 许可声明: 这不是一个自由软件！您只能在购买源代码后或者经 phpstorm_company_name_str 官方授权的前提下对程序代码进行修改和使用，
 * 任何企业或个人都不得在源代码上以任何形式任何目的的再次发布和销售以及镜像或复制,包括但不限于已购买源代码和官方授权者。
 * 警 告  : 如若您或贵司未经正式购买渠道获得授权，请立即停止侵权行为，我们已经委派 phpstorm_company_auth_legal 作为我们侵权
 * 起诉的法律代表，还请您或贵司尊重商业版权以及劳动成果，自觉停止侵权行为。您也可匿名举报侵权行为，一旦您的举报被证实，我们
 * 将会以本版本零售价的 phpstorm_company_product_percent_money% 现金给您，以便作为您的辛苦奖励。同时，我们也将竭尽全力保证您的隐私安全。举报邮箱: phpstorm_company_product_report_mail
 * 协议约定: 本产品遵守 << phpstorm_company_product_protocol >> 的约束,您或贵司也可以访问 phpstorm_company_product_protocol 了解更多详情信息。
 * 致 谢  : 感谢您或贵司对我们产品的支持和热爱，我们将不定期对本产品进行更新和修复bug。还请您和贵司多多指导。更多问题资讯请访问
 * phpstorm_company_product_help_url ,如果您正在对此版本进行二次开发，提bug或者需求可以发送到@author邮箱,或者提交工单。
 * 工单地址是: phpstorm_company_product_ticket_url 我们将尽快为您提出合理的解决方案。
 * 其 他  : 您或贵司也可以登录 phpstorm_company_product_doc_url 查看相关的文档资料以及FAQ！
 * ***************************************************************************************************************************
 * @product content_cms
 * @desc
 * @author justary <justary@126.com>
 * @date 2024/06/26 09:02
 * @version phpstorm_company_product_version
 * @copyright phpstorm_company_product_copyright
 */

/**
 * @package app\data\logic
 *
 * @filesource PageLogic.php
 * @author justary <justary@126.com>
 * @date 2024/06/26 09:02
 * @link phpstorm_product_licence
 * @version phpstorm_company_product_version
 * @copyright phpstorm_company_product_copyright
 */


namespace app\data\logic;

use app\data\components\Mail;
use app\data\components\Oss;
use app\data\model\QuestionCategoryModel;
use app\data\model\CmsPageModel;
use app\data\service\AdPositionService;
use app\data\service\AdService;
use app\data\service\BaseService;
use app\data\service\CaseCategoryService;
use app\data\service\CaseService;
use app\data\service\CmsCatService;
use app\data\service\CmsLabelConnService;
use app\data\service\CmsLabelService;
use app\data\service\CmsPagePartService;
use app\data\service\CmsPageService;
use app\data\service\CmsPendantsService;
use app\data\service\CmsService;
use app\data\service\CmsSitesService;
use app\data\service\DownloadCategoryService;
use app\data\service\DownloadLinkService;
use app\data\service\DownloadService;
use app\data\service\FeedBackService;
use app\data\service\FormAllService;
use app\data\service\FormValueService;
use app\data\service\ConfigService;
use app\data\service\MailVerifyService;
use app\data\service\NavigateService;
use app\data\service\ProductsExtCatRelationsService;
use app\data\service\ProductsFieldsService;
use app\data\service\QuestionCategoryService;
use app\data\service\QuestionService;
use app\data\service\PhotosService;
use app\data\service\ProductsCategoryService;
use app\data\service\ProductsFilesService;
use app\data\service\ProductsService;
use app\data\service\TagsLibService;
use app\data\valid\NavigateValid;
use think\db\Query;
use think\exception\ValidateException;
use think\facade\Env;
use think\facade\Log;

class PageLogic extends BaseLogic
{
    protected NavigateService $navigateService;
    protected AdService $adService;
    protected AdPositionService $adPositionService;
    protected CmsPageService $cmsPageService;
    protected CmsPagePartService $cmsPagePartService;
    protected CmsCatService $cmsCatService;
    protected CmsService $cmsService;
    protected MailVerifyService $mailVerifyService;
    protected CmsLabelService $labelService;
    protected FeedBackService $feedBackService;
    protected ConfigService $configService;
    protected CmsLabelConnService $cmsLabelConnService;
    protected CmsSitesService $cmsSitesService;
    protected CmsPendantsService $cmsPendantsService;
    protected ProductsService $productService;
    protected ProductsCategoryService $productCategoryService;
    protected DownloadService $downloadService;
    protected DownloadCategoryService $downloadCategoryService;
    protected DownloadLinkService $downloadLinkService;
    protected QuestionService $questionService;
    protected QuestionCategoryService $questionCategoryService;
    protected PhotosService $photosService;
    protected ProductsFilesService $productsFilesService;
    protected CaseCategoryService $caseCategoryService;
    protected Caseservice $caseService;
    protected ProductsFieldsService $productsFieldsService;
    protected TagsLibService $tagsLibService;

    protected ProductsExtCatRelationsService $productsExtCatRelationsService;

    public function __construct()
    {
        $this->navigateService = new NavigateService();
        $this->adService = new AdService();
        $this->adPositionService = new AdPositionService();
        $this->cmsPageService = new CmsPageService();
        $this->cmsPagePartService = new CmsPagePartService();
        $this->cmsCatService = new CmsCatService();
        $this->cmsService = new CmsService();
        $this->mailVerifyService = new MailVerifyService();
        $this->labelService = new CmsLabelService();
        $this->feedBackService = new FeedBackService();
        $this->configService = new ConfigService();
        $this->cmsLabelConnService = new CmsLabelConnService();
        $this->cmsSitesService = new CmsSitesService();
        $this->cmsPendantsService = new CmsPendantsService();
        $this->downloadService = new DownloadService();
        $this->downloadCategoryService = new DownloadCategoryService();
        $this->downloadLinkService = new DownloadLinkService();
        $this->questionService = new QuestionService();
        $this->questionCategoryService = new QuestionCategoryService();
        // 产品模块
        $this->productCategoryService = new ProductsCategoryService();
        $this->productService = new ProductsService();
        // 图片管理
        $this->photosService = new PhotosService();
        // 产品资源管理
        $this->productsFilesService = new ProductsFilesService();
        // 案例管理
        $this->caseCategoryService = new CaseCategoryService();
        $this->caseService = new CaseService();
        $this->tagsLibService = new TagsLibService();
        //拓展分类
        $this->productsExtCatRelationsService = new ProductsExtCatRelationsService();
    }

    public function getQuestionListForType($type): array
    {
        $res = $this->questionCategoryService->getOne('*', ['id' => $type], []);
        if (isset($res['id'])) {
            $where['cat_id'] = $res['id'];
            $result = $this->questionService->getAll('*', $where, 'sort desc');
            return $result;
        } else {
            return [];
        }
    }

    public function getTagsLib()
    {
        $tags = $this->tagsLibService->getAll('*', ['is_show' => 1], 'order desc', []);
        return $tags;
    }

    public function getNavigateId(string $action): array
    {
        $field = '*';
        $where = [
            'en_name' => $action
        ];
        $withs = ['parentNav' => function (Query $query) {
            $query->with('children');
        },
            'relationPage'
        ];
        return $this->navigateService->getOne($field, $where, $withs);
    }

    public function getNavigateList($params = []): array
    {
        $where = [];
        if (array_key_exists('isshow', $params)) {
            $where[] = [
                ['isshow', '=', $params['isshow']]
            ];
        }
        $list = $this->navigateService->getList($where);
        return formatTree(getTree($list));
    }

    public function getNavigateGeneralList($field = '*', $where = [], $order = ''): array
    {
        return $this->navigateService->getAll($field, $where, $order);
    }

    public function getFirstNavigateCount(): int
    {
        return $this->navigateService->total(['parent_id' => 0, 'isshow' => 1]);
    }

    public function getConfigList(): array
    {
        $field = '*';
        $where = [
            'parent_id' => 0,
            'isshow' => 1
        ];
        $order = '';
//        return $this->configService->getAll($field, $where, $order);
        return $this->configService->getAllByRelation($field, $where, $order);
    }

    public function getQuestionList($params = []): array
    {
        $field = '*';
        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $where = [];
        $order = 'create_time desc';
        $result = $this->questionService->getPageList($pageIndex, $pageSize, $where, $field, $order);
        if (array_key_exists('all', $params)) {
            $result = $this->questionService->getAll($field, $where, $order);
        }
        return $result;
    }

    public function getQuestionCategoryList(): array
    {
        $field = '*';
        $where = [];
        $order = '';
        return $this->questionCategoryService->getAll($field, $where, $order);
    }

    public function getLabelList(): array
    {
        $field = '*';
        $where = [];
        $order = '';
        return $this->labelService->getAll($field, $where, $order);
    }

    /**
     * 下载列表
     * @param $params
     * @return array
     */
    public function getDownloadList($params): array
    {
        $field = '*';
        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $where = [];
        if (array_key_exists('cat_id', $params) && $params['cat_id']) {
            $where[] = ['cat_id', '=', $params['cat_id']];
        }
        if (array_key_exists('keywords', $params) && $params['keywords']) {
            $keywords = $params['keywords'];
            $where[] = function ($query) use ($keywords) {
                $query->whereLike('title', '%' . $keywords . '%');
            };
        }

        if (array_key_exists('is_top', $params) && $params['is_top']) {
            $where[] = ['is_top', '=', $params['is_top']];
        }
        $withs = ['downloadCategory'];
        $order = 'create_time desc';
        $result = $this->downloadService->getPageList($pageIndex, $pageSize, $where, $field, $order, $withs);
        if (array_key_exists('all', $params)) {
            $result = $this->downloadService->getAll($field, $where, $order, $withs);
        }
        return $result;
    }

    public function getDownloadLinkList(): array
    {
        $field = '*';
        $where = [];
        $order = '';
        return $this->downloadLinkService->getAll($field, $where, $order);
    }

    public function getDownloadCategoryList(): array
    {
        $field = '*';
        $where = [];
        $order = '';
        $withs = ['downloads'];
        $list = $this->downloadCategoryService->getAll($field, $where, $order, $withs);
        return formatTree(getTree($list, 'cat_id'));
    }


    public function getCmsCatList($params = []): array
    {
        $field = '*';
        $where = [];
        $order = 'sort_order desc,cat_id asc';
        $withs = ['cmsList', 'navigate'];
        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        if (array_key_exists('cat_ids', $params)) {
            $where[] = function ($query) use ($params) {
                $query->where('cat_id', 'in', $params['cat_ids']);
            };
        }
        if (array_key_exists('is_show', $params)) {
            $where[] = ['is_show', '=', $params['is_show']];
        }
        $result = $this->cmsCatService->getPageList($pageIndex, $pageSize, $where, $field, $order, $withs);
        if (array_key_exists('all', $params)) {
            $result = $this->cmsCatService->getAll($field, $where, $order, $withs);
        }
        return $result;
    }

    public function getConfigCount(): int
    {
        $where = [];
        return $this->labelService->total($where);
    }

    public function getQuestionCount(): int
    {
        $where = [];
        return $this->questionService->total($where);
    }

    public function getQuestionCategoryCount(): int
    {
        $where = [];
        return $this->questionCategoryService->total($where);
    }

    public function getLabelCount(): int
    {
        $where = [];
        return $this->labelService->total($where);
    }

    public function getDownloadCount(): int
    {
        $where = [];
        return $this->downloadService->total($where);
    }

    public function getDownloadLinkCount(): int
    {
        $where = [];
        return $this->downloadLinkService->total($where);
    }

    public function getDownloadCategoryCount(): int
    {
        $where = [];
        return $this->downloadCategoryService->total($where);
    }

    public function getCmsCatCount(): int
    {
        $where = [];
        return $this->cmsCatService->total($where);
    }

    public function getAdList(int $position_id): array
    {
        $field = '*';
        $where = [];
        if ($position_id) {
            $where[] = ['position_id', '=', $position_id];
        }
        $order = '';
        return $this->adService->getAll($field, $where, $order);
    }

    public function getAdPositionList(): array
    {
        $field = '*';
        $where = [];
        $order = '';
        $withs = ['relationPage', 'adList'];
        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $result = $this->adPositionService->getPageList($pageIndex, $pageSize, $where, $field, $order, $withs);
        return $result;
    }

    public function getPageList($params): array
    {
        try {
            $field = '*';
            $where = $this->getPageParams($params);
            $order = 'order_id desc,page_id desc';
            $with = [
                'part' => function ($q) {
                    $q->where('is_show', 1);
                },
                'children'
            ];
            $list = $this->getSubList($this->cmsPageService, $field, $where, $order, $with, [], 'page_id');
            return $list;
        } catch (\Exception $exception) {
            Log::debug("\n" . $exception->getMessage() .
                "\n" . $exception->getFile() . ":" . $exception->getLine()
            );
            return [];
        }

    }

    public function getCmsList($params): array
    {
        $field = '*';
        $where = [];
        if (array_key_exists('cat_id', $params)) {
            $where[] = [
                ['cat_id', '=', $params['cat_id']],
            ];
        }
        if (array_key_exists('is_show', $params)) {
            $where[] = [
                ['is_show', '=', $params['is_show']],
            ];
        }
        if (array_key_exists('keywords', $params)) {
            $keywords = $params['keywords'];
            if (gettype($keywords) === 'array') {
                $where[] = function (Query $query) use ($keywords) {
                    for ($i = 0; $i < count($keywords); $i++) {
                        $query->whereOr('title', 'like', '%' . $keywords[$i] . '%');
                    }
                };
            } else {
                $where[] = function ($query) use ($keywords) {
                    $query->whereLike('title', '%' . $keywords . '%');
                };
            }
        }

        $order = 'sort_order desc,showtime desc';
        $list = $this->cmsService->getAll($field, $where, $order, ['cmsCat']);
        return $list;
    }

    public function getPagePartList(int $page_id): array
    {
        $field = '*';
        $where = [];
        if ($page_id) {
            $where[] = ['page_id', '=', $page_id];
        }
        $order = 'sort asc,id asc';
        return $this->cmsPagePartService->getAll($field, $where, $order);
    }

    public function getAdPositionCount(): int
    {
        $where = [];
        return $this->adPositionService->total($where);
    }

    public function getPageCount($params): int
    {
        $where = $this->getPageParams($params);
        return $this->cmsPageService->total($where);
    }

    public function getPagePartCount(int $page_id): int
    {
        $where = [
            'page_id' => $page_id,
        ];
        return $this->cmsPagePartService->total($where);
    }

    public function getPageData($nav_id): array
    {
        $field = '*';
        $where = [
            'nav_id' => $nav_id
        ];
        return $this->cmsPageService->getOne($field, $where);
    }

    public function getPagePartData(int $id, int $page_id): array
    {
        $field = '*';
        $where = [
            'page_id' => $page_id,
            'id' => $id,
        ];
        return $this->cmsPagePartService->getOne($field, $where);
    }

    public function getAdData($field = '*', $where = []): array
    {

        $res = $this->adPositionService->getOne($field, $where);
        if ($res) {
            $f = 'ad_id,media_type,ad_name,ad_link,ad_code,mad_code,enabled,des,video_url';
            $w = [
                'position_id' => $res['position_id']
            ];
            $o = 'orderid asc';
            $list = $this->adService->getAll($f, $w, $o);
        } else {
            $list = [];
        }

        return $list;
    }

    public function getMailDetail($email, $scene, $code): array
    {
        try {
            $where = [
                'email' => $email,
                'scene' => $scene,
                'code' => $code
            ];
            $order = 'create_time desc';
            $res = $this->mailVerifyService->getAll('timeout', $where, $order);
            if (is_array($res) && !empty($res)) {
                if (time() > $res[0]['timeout']) {
                    $res = false;
                } else {
                    $res = true;
                }
            } else {
                $res = false;
            }
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewMailCode($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            //发送邮件
            $options = [
                'Username' => Env::get('MAIL.MAIL_USERNAME'),
                'Password' => Env::get('MAIL.MAIL_PASSWORD'),
                'Host' => Env::get('MAIL.MAIL_HOST'),
                'Port' => Env::get('MAIL.MAIL_PORT'),
            ];
            $mail = new Mail($options);
            $op = match ($data['scene']) {
                "1" => '登录',
                "2" => '注册',
                "3" => '重置密码',
                default => '账户',
            };
            $mailSend = $mail
                ->from(Env::get('MAIL.MAIL_USERNAME'), 'ctmoncms')
                ->receive($data['email'], '')
                ->send(false, '验证码通知', '您当前正在进行【' . $op . '】操作，验证码是' . $data['code'] . ',验证码有效期为5分钟。请及时验证操作。');
            if ($mailSend['state'] === false) {
                return $this->responseInfo(false, 'FAILURE');
            }
            $ret = $this->mailVerifyService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewPagePart($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->cmsPagePartService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 创建文章分类
     * @param $data
     * @return array
     */
    public function createCmsCat($data): array
    {
        try {
            $ret = $this->cmsCatService->insert($data);
            if ($ret) {
                buildRoute($data['cat_name'], '/index/page/blog', $data['urlrewriter'], ['id' => $ret], 'blog');
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewConfig($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->configService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewDownloadCategory($data): array
    {
        try {
            $ret = $this->downloadCategoryService->insert($data);
            if ($ret) {
                buildRoute($data['cat_name'], '/index/page/download', $data['urlrewriter'], ['id' => $ret]);
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewDownload($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->downloadService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewDownloadLink($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->downloadLinkService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewCms($data): array
    {
        try {
            $ret = $this->cmsService->insert($data);
            if (isset($data['label_ids'])) {
                $this->cmsService->txBegin();
                $ids = explode(",", $data['label_ids']);
                foreach ($ids as $id) {
                    $ret1 = $this->cmsLabelConnService->insert(['cms_id' => $ret, 'label_id' => $id]);
                    if (!$ret1) {
                        $this->cmsService->txRollback();
                        return $this->responseInfo(false, 'FAILURE');
                    }
                }
            }
            if ($ret) {
                // 添加页面
                buildRoute($data['title'], '/index/page/bloginfo', $data['urlrewriter'], ['id' => $ret], 'blog');
                $this->cmsService->txCommit();
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewQuestion($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->questionService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewAd($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->adService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewQuestionCategory($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->questionCategoryService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewAdPosition($data): array
    {
        try {
            //        validate(PageValid::class)
            //          ->scene('add')
            //          ->check($data);
            //TODO 二期工程
            $ret = $this->adPositionService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function createNewPage($data): array
    {
        try {
            //        validate(PageValid::class)
//          ->scene('add')
//          ->check($data);
            if (array_key_exists('page_type', $data)) {
                $action = "";
                switch ($data['page_type']) {
                    case 2:
                        $action = 'product';
                        break;
                    case 3:
                        $action = 'cases';
                        break;
                    default:
                        $action = 'index';
                        break;
                }
                $data['nav_id'] = $this->getNavigateId($action)['id'];
            }
            //TODO 二期工程
            $ret = $this->cmsPageService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 创建导航栏
     * @param $data
     * @return array
     */
    public function createNewNavigate($data): array
    {
        try {
            $ret = $this->navigateService->insert($data);
            if ($ret) {
                // 创建路由
                if ($data['type'] == 1) {
                    buildRoute($data['name'], $data['url'], $data['writeurl']);
                }
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updatePagePart($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->cmsPagePartService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateConfig($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('update')
            //        ->check($checkData);
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->configService->updateAll($data['data']);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateLabel($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('update')
            //        ->check($checkData);
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->labelService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateDownloadCategory($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('update')
            //        ->check($checkData);
            //TODO 二期开发
            $where = [
                'cat_id' => $id
            ];

            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->downloadCategoryService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['urlrewriter'];
            $title = $item['cat_name'];
            if (array_key_exists('urlrewriter', $data)) {
                $buildUrl = $data['urlrewriter'];
            }
            if (array_key_exists('title', $data)) {
                $title = $data['cat_name'];
            }
            updateRoute($title, '/index/page/download', $buildUrl, $removeUrl, ['id' => $id]);


            $ret = $this->downloadCategoryService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateDownloadLink($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('update')
            //        ->check($checkData);
            //TODO 二期开发
            $where = [
                'link_id' => $id
            ];
            $ret = $this->downloadLinkService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateDownload($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('update')
            //        ->check($checkData);
            //TODO 二期开发
            $where = [
                'down_id' => $id
            ];
            $ret = $this->downloadService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateCms($id, $data, $checkData): array
    {
        try {
            //TODO 二期开发
            $where = [
                'article_id' => $id
            ];

            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->cmsService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['urlrewriter'];
            $title = $item['title'];
            if (array_key_exists('urlrewriter', $data)) {
                $buildUrl = $data['urlrewriter'];
            }
            if (array_key_exists('title', $data)) {
                $title = $data['title'];
            }
            updateRoute($title, '/index/page/bloginfo', $buildUrl, $removeUrl, ['id' => $id], 'blog');

            $ret = $this->cmsService->update($where, $data);

            if ($ret) {
                $this->cmsService->txCommit();
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            Log::error($e->getMessage());
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateCmsCat($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'cat_id' => $id
            ];
            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->cmsCatService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['urlrewriter'];
            $title = $item['cat_name'];
            if (array_key_exists('urlrewriter', $data)) {
                $buildUrl = $data['urlrewriter'];
            }
            if (array_key_exists('cat_name', $data)) {
                $title = $data['cat_name'];
            }
            updateRoute($title, '/index/page/blog', $buildUrl, $removeUrl, ['id' => $id], 'blog');

            $ret = $this->cmsCatService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateQuestionCategory($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->questionCategoryService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateQuestion($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->questionService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateAd($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'ad_id' => $id
            ];
            $ret = $this->adService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateAdPosition($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'position_id' => $id
            ];
            $ret = $this->adPositionService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updatePage($id, $data, $checkData): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'page_id' => $id
            ];
            $ret = $this->cmsPageService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function updateNavigate($id, $data, $checkData): array
    {
        try {
            validate(NavigateValid::class)
                ->scene('update')
                ->check($checkData);
            $where = [
                'id' => $id
            ];
            $ret = $this->navigateService->update($where, $data);
            if ($ret) {
                $item = $this->navigateService->getOne("*", $where);
                $removeUrl = $buildUrl = $item['writeurl'];
                $title = $item['name'];
                if (array_key_exists('writeurl', $data)) {
                    $buildUrl = $data['writeurl'];
                }
                if (array_key_exists('name', $data)) {
                    $title = $data['name'];
                }
                updateRoute($title, $item['url'], $buildUrl, $removeUrl);


                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getQuestionCategoryDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $res = $this->questionCategoryService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getQuestionDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $res = $this->questionService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getAdDetail($id): array
    {
        try {
            $where = [
                'ad_id' => $id
            ];
            $res = $this->adService->getOne('*', $where, ['adPosition']);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getAdPositionDetail($id): array
    {
        try {
            $where = [
                'position_id' => $id
            ];
            $res = $this->adPositionService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    public function getPagePartDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $res = $this->cmsPagePartService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getConfigDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $res = $this->configService->getOne('*', $where);
            if ($res) {
                $subConfigList = $this->configService->getAll('*', ['parent_id' => $id], '');
                $res['subConfigList'] = $subConfigList;
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getCmsDetail($id): array
    {

        try {

            $where = [
                'article_id' => $id
            ];
            $withs = ['cmsCat'];
            $res = $this->cmsService->getOne('*', $where, $withs);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getDownloadCategoryDetail($id): array
    {
        try {

            $where = [
                'cat_id' => $id
            ];
            $res = $this->downloadCategoryService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getDownloadLinkDetail($id): array
    {
        try {

            $where = [
                'link_id' => $id
            ];
            $res = $this->downloadLinkService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getDownloadDetail($id): array
    {
        try {

            $where = [
                'down_id' => $id
            ];
            $withs = ['downloadCategory'];
            $res = $this->downloadService->getOne('*', $where, $withs);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getCmsCatDetail($id): array
    {
        try {

            $where = [
                'cat_id' => $id
            ];
            $withs = ['cmsList'];
            $res = $this->cmsCatService->getOne('*', $where, $withs);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getPageDetail($id, $data): array
    {
        try {
            //      validate(NavigateValid::class)
//        ->scene('update')
//        ->check($data);
            $where = [
                'page_id' => $id
            ];
            $withs = [
                'part' => function ($q) {
                    $q->where('is_show', 1);
                },
                'children' => function ($q) {
                    $q->where('is_show', 1);
                }
            ];
            $res = $this->cmsPageService->getOne('*', $where, $withs);
            if (array_key_exists('nav_id', $res) && $res['nav_id']) {
                $res['navName'] = $this->navigateService->getOne('name', ['id' => $res['nav_id']])['name'];
            }


            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function getNavigateDetail($id, $data): array
    {
        try {
//            validate(NavigateValid::class)
//                ->scene('update')
//                ->check($data);
            $where = [
                'id' => $id
            ];
            $res = $this->navigateService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deletePagePart($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'id' => $id
            ];
            $ret = $this->cmsPagePartService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteCmsLabelConn($cms_id, $label_id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('delete')
            //        ->check($checkData);
            $where = [
                'cms_id' => $cms_id,
                'label_id' => $label_id
            ];
            $ret = $this->cmsLabelConnService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteConfig($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
            //        ->scene('delete')
            //        ->check($checkData);
            $where = [
                'id' => $id
            ];
            $ret = $this->configService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteDownload($id, $checkData = ''): array
    {

        try {
            //      validate(PageValid::class)
            //        ->scene('delete')
            //        ->check($checkData);
            $where = [
                'down_id' => $id
            ];
            $ret = $this->downloadService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteDownloadLink($id, $checkData = ''): array
    {

        try {
            //      validate(PageValid::class)
            //        ->scene('delete')
            //        ->check($checkData);
            $where = [
                'link_id' => $id
            ];
            $ret = $this->downloadLinkService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteDownloadCategory($id, $checkData = ''): array
    {

        try {
            //      validate(PageValid::class)
            //        ->scene('delete')
            //        ->check($checkData);
            $where = [
                'cat_id' => $id
            ];
            $item = $this->downloadCategoryService->getOne("*", $where);
            removeRoute($item['urlrewriter']);
            $ret = $this->downloadCategoryService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteLabel($id, $checkData = ''): array
    {

        try {
            //      validate(PageValid::class)
            //        ->scene('delete')
            //        ->check($checkData);
            $where = [
                'id' => $id
            ];
            $ret = $this->labelService->softDel($where);
            $ret1 = $this->cmsLabelConnService->getAll('cms_id', ['label_id' => $id], '');
            if ($ret1) {
                return $this->responseInfo(false, 'FAILURE');
            }
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteCms($id, $checkData = ''): array
    {
        try {
            $where = [
                'article_id' => $id
            ];
            $item = $this->cmsService->getOne("*", $where);
            removeRoute($item['urlrewriter'], 'blog');

            $ret = $this->cmsService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteCmsCat($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'cat_id' => $id
            ];
            $cmsRet = $this->cmsService->getAll('*', $where, '');
            if ($cmsRet) {
                $ret = false;
            } else {
                $ret = $this->cmsCatService->softDel($where);
            }
            if ($ret) {
                $item = $this->cmsCatService->getOne("*", $where);
                removeRoute($item['urlrewriter'], 'blog');
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteQuestionCategory($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'id' => $id
            ];
            $ret = $this->questionCategoryService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteQuestion($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'id' => $id
            ];
            $ret = $this->questionService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    public function deleteAd($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'ad_id' => $id
            ];
            $ret = $this->adService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteAdPosition($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'position_id' => $id
            ];
            $ret = $this->adPositionService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deletePage($id, $checkData = ''): array
    {
        try {
            //      validate(PageValid::class)
//        ->scene('delete')
//        ->check($checkData);
            $where = [
                'page_id' => $id
            ];
            $ret = $this->cmsPageService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    public function deleteNavigate($id, $checkData, $multi = false): array
    {
        try {

            $is_del = true;

            if ($multi) {
                $where[] = ['id', 'in', $id];
                $navigateList = $this->navigateService->getAll('parent_id', $where, '');
                if ($navigateList) {
                    foreach ($navigateList as $item => $value) {
                        if ($value['parent_id'] !== 0) {
                            $is_del = false;
                        }
                    }
                } else {
                    $is_del = true;
                }
                if ($is_del) {
                    $newWhere[] = ['id', 'in', $id];
                    $ret = $this->navigateService->softDel($newWhere);
                } else {
                    $ret = false;
                }
            } else {
                $where = [
                    'parent_id' => $id
                ];
                $navDetail = $this->navigateService->getOne('id', $where);
                if ($navDetail) {
                    $ret = false;
                } else {
                    $detail = $this->navigateService->getOne('*', ['id' => $id]);
                    removeRoute($detail['writeurl']);
                    $ret = $this->navigateService->softDel(['id' => $id]);
                }
            }
            if ($ret) {

                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 获取置顶文章
     * @return array
     */
    public function getArticleTopOne()
    {
        $field = '*';
        $where = [
            'is_top' => 1,
            'is_show' => 1
        ];
        $withs = ['cmsCat'];
        return $this->cmsService->getOne($field, $where, $withs);
    }

    /**
     * 分页查询文章列表
     * @param $pageIndex
     * @param $pageSize
     */
    public function getArticleListByPages($pageIndex, $pageSize, $cat = 1, $condition = null, $search = ""): array
    {
        try {


            $where = [
                'cat_id' => $cat
            ];
            if ($cat == null) {
                unset($where['cat_id']);
            }

            if ($search) {
                $keywords = $search['keywords'] ?? null;
                $year = $search['year'] ?? null;
                $tag = $search['tag'] ?? null;
                if ($keywords) {
                    $where[] = function ($query) use ($keywords) {
                        $query->whereLike('title', '%' . $keywords . '%');
                    };
                }
                if ($tag) {
                    $where[] = function ($query) use ($tag) {
                        $query->whereLike('tags', '%' . $tag . '%');
                    };
                    unset($where['cat_id']);
                }
                if ($year) {
                    $where[] = function (Query $query) use ($year) {
                        $query->whereYear('showtime', $year);
                    };
                }
            }


            if ($condition) {
                if (array_key_exists('is_show', $condition)) {
                    $where[] = function ($query) use ($condition) {
                        $query->where('is_show', $condition['is_show']);
                    };
                }
            }


            $fields = "*";
            $order = 'is_top desc,create_time desc,showtime desc';
            $withs = ['cmsCat'];
            return $this->cmsService->getPageList($pageIndex, $pageSize, $where, $fields, $order, $withs);
        } catch (\Exception $exception) {
            logError($exception);
            return [];
        }
    }

    /**
     * 获取推荐文章
     * @return array
     */
    public function getArticleForRecommend(): array
    {
        $field = '*';
        $where = [
            'is_best' => 1,
            'is_show' => 1
        ];
        $orderBy = 'sort_order asc,article_id desc';
        return $this->cmsService->getAll($field, $where, $orderBy);
    }

    public function getArticleForUp($id): array
    {
        $field = '*';
        $where = [
            'article_id' => $id - 1,
        ];
        return $this->cmsService->getOne($field, $where);
    }

    public function getArticleForDown($id): array
    {
        $field = '*';
        $where = [
            'article_id' => $id + 1,
        ];
        return $this->cmsService->getOne($field, $where);
    }


    /**
     * 添加新的回馈信息
     * @param $data
     * @return array
     */
    public function createNewFeedBack($data): array
    {
        try {
            $ret = $this->feedBackService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 获取上下一条文章
     * @param $id
     * @return array
     */
    public function getArticleForPreAndNext($id): array
    {
        $prevWhere = [
            ['article_id', '<', $id]
        ];
        $nextWhere = [
            ['article_id', '>', $id]
        ];
        $prev = $this->cmsService->getOne("*", $prevWhere);
        $next = $this->cmsService->getOne("*", $nextWhere);
        return [
            'prev' => $prev,
            'next' => $next
        ];
    }

    /**
     * 查询cms_id不为空的标签
     * @return array
     */
    public function getLabelListByFrotend(): array
    {
        $field = '*';
        $where = [
            ['cms_id', '<>', 'null']
        ];
        $order = '';
        return $this->labelService->getAll($field, $where, $order);
    }

    /**
     * 根据导航id获取导航信息
     * @param $navId
     * @return array
     */
    public function getNavigateDetailByFrontend($navId): array
    {
        return $this->navigateService->getOne("*", ['id' => $navId]);
    }

    public function getSubPage($cms_id): array
    {
        return $this->cmsService->getOne('*', ['article_id' => $cms_id]);
    }


    /**
     * 获取用户反馈列表
     * @param $params
     * @return array
     */
    public function getFeedBackList($params): array
    {
        $fields = "*";
        $where = [];
        if (array_key_exists('ids', $params)) {
            $where[] = ['msg_id', 'in', explode(',', $params['ids'])];
        }

        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $order = 'create_time desc';
        return $this->feedBackService->getPageList($pageIndex, $pageSize, $where, $fields, $order);
    }

    /**
     * 获取用户反馈总数量
     * @return int
     */
    public function getFeedBackCount($params): int
    {
        $where = [];
        if (array_key_exists('ids', $params)) {
            $where[] = ['msg_id', 'in', explode(',', $params['ids'])];
        }
        return $this->feedBackService->total($where);
    }

    /**
     * 根绝配置的code值获取配置详情
     * @param $code
     * @return array
     */
    public function getConfigDetailByCode($code)
    {
        if (empty($code)) {
            return [];
        }
        $where = [
            'code' => $code
        ];
        $with = [
            'subConfig'
        ];
        $res = $this->configService->getOne('*', $where, $with);
        $subConfig = $res['subConfig'];
        // 直接读取根选项
        for ($i = 0; $i < count($subConfig); $i++) {
            $res[$subConfig[$i]['code']] = $subConfig[$i]['value'];
        }
        if ($res) {
            return $this->responseInfo(true, 'SUCCESS', $res);
        } else {
            return $this->responseInfo(false, 'FAILURE');
        }
    }

    /**
     * 删除反馈信息
     * @param $id integer 信息id
     * @return array
     */
    public function deleteFeedback($id)
    {
        try {
            $where = [
                'msg_id' => $id
            ];
            $ret = $this->feedBackService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    /**
     * 更新反馈信息
     * @param $id integer 信息id
     * @param $data array 信息数据
     * @return array
     */
    public function updateFeedback($id, $data)
    {

        try {
            //      validate(PageValid::class)
//        ->scene('update')
//        ->check($checkData);
            //TODO 二期开发
            $where = [
                'msg_id' => $id
            ];
            $ret = $this->feedBackService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 上传文件
     * @param $inputFilesName string 上传的name值
     * @return array|void
     */
    public function uploadFiles()
    {
        // 获取表单上传文件
        $files = request()->file('files');
        $ossConfig = $this->getConfigDetailByCode('oss')['data'];
        try {
            $savename = [];
            foreach ($files as $file) {
                $fileName = $file->getOriginalName();
                $extension_file = pathinfo($fileName, PATHINFO_EXTENSION);
                $extension = match (strtolower($extension_file)) {
                    'gif', 'png', 'jpg', 'jpeg' => 'images',
                    'mp4' => 'video',
                    'mp3' => 'audio',
                    default => 'other',
                };
                $savename[] = \think\facade\Filesystem::disk('public')->putFile($extension, $file);
            }
            $ok = array($savename);
            if ($ossConfig['IS_ENABLED'] == 1) {
                $baseDir = root_path() . 'public' . DIRECTORY_SEPARATOR;
                $id = $ossConfig['ACCESS_KEY_ID'];
                $secret = $ossConfig['ACCESS_KEY_SECRET'];
                $endpoint = $ossConfig['ENDPOINT'];
                $bucket = $ossConfig['BUCKET'];
                $oss = new Oss($id, $secret, $endpoint);
                $fileDir = 'storage' . DIRECTORY_SEPARATOR;
                $ok = 0;
                foreach ($savename as $key => $value) {
                    $result = $oss->upload($bucket, $fileDir . $value, $baseDir . $fileDir . $value);
                    if ($result['state']) {
                        if ($result['data']['info']['http_code'] == 200) {
                            $ok++;
                        }
                    }
                }
            }
            $bind_domain = $ossConfig['BIND_DOMAIN'];
            $product_domain = $ossConfig['PRODUCT_DOMAIN'];


            $responseData = [
                'files' => $savename,
                'count' => $ok,
                'local_url' => DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR,
                'bind_url' => $bind_domain,
                'product_url' => $product_domain
            ];

            return $this->responseInfo(true, 'SUCCESS', $responseData);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 获取站点列表
     * @param $params
     * @return mixed
     */
    public function getCmsSitesList($params)
    {
        $fields = "*";
        $where = [];
        if (array_key_exists('is_show', $params)) {
            $where[] = ['is_show', '=', $params['is_show']];
        }

        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $order = 'sort desc,create_time desc';
        return $this->cmsSitesService->getPageList($pageIndex, $pageSize, $where, $fields, $order);
    }

    /**
     * 创建新站点
     * @param $data
     * @return array
     */
    public function createCmsSites($data): array
    {
        try {
            //TODO 二期工程
            $ret = $this->cmsSitesService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 更新站点信息
     * @param $id
     * @param $data
     * @return array
     */
    public function updateCmsSites($id, $data): array
    {
        try {
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->cmsSitesService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 软删除站点信息
     * @param $id
     * @return array
     */
    public function deleteCmsSites($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $ret = $this->cmsSitesService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 获取站点详情
     * @param $id
     * @return array
     */
    public function getCmsSitesDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $res = $this->cmsSitesService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 获取挂件列表
     * @param $params
     * @return mixed
     */
    public function getCmsPendantsList($params): mixed
    {
        $fields = "*";
        $where = [];
        if (array_key_exists('is_show', $params)) {
            $where[] = ['is_show', '=', $params['is_show']];
        }

        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $order = 'sort desc,create_time desc';
        return $this->cmsPendantsService->getPageList($pageIndex, $pageSize, $where, $fields, $order);
    }

    /**
     * 添加挂件
     * @param $data
     * @return array
     */
    public function createCmsPendants($data): array
    {
        try {
            //TODO 二期工程
            $ret = $this->cmsPendantsService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 更新挂件
     * @param $id
     * @param $data
     * @return array
     */
    public function updateCmsPendants($id, $data): array
    {
        try {
            //TODO 二期开发
            $where = [
                'id' => $id
            ];
            $ret = $this->cmsPendantsService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 删除挂件
     * @param $id
     * @return array
     */
    public function deleteCmsPendants($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $ret = $this->cmsPendantsService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 获取挂件详情
     * @param $id
     * @return array
     */
    public function getCmsPendantsDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $res = $this->cmsPendantsService->getOne('*', $where);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 页面筛选参数
     * @param array $params
     * @return array
     */
    private function getPageParams(array $params = []): array
    {
        $where = [];

        $parentId = null;
        if (array_key_exists('parent_id', $params)) {
            $parentId = $params['parent_id'];
        }
        $where['parent_id'] = $parentId;
        // 判断页面类型
        $pageType = 1;
        if (array_key_exists('page_type', $params)) {
            $pageType = $params['page_type'];
        }
        $where['page_type'] = $pageType;
        return $where;
    }


    /**
     * 获取前后一页
     * @param $id
     * @param $params
     * @return array
     */
    public function getPageForPreAndNext($id, $params = []): array
    {
        $prevWhere[] = [
            ['page_id', '<', $id],
            ['parent_id', '<>', 0]
        ];
        $nextWhere[] = [
            ['page_id', '>', $id],
            ['parent_id', '<>', 0]
        ];
        if (array_key_exists('page_type', $params)) {
            $prevWhere[] = ['page_type', '=', $params['page_type']];
            $nextWhere[] = ['page_type', '=', $params['page_type']];
        }

        $prev = $this->cmsPageService->getOne("*", $prevWhere);
        $next = $this->cmsPageService->getOne("*", $nextWhere);
        return [
            'prev' => $prev,
            'next' => $next
        ];
    }

    /**
     * 分页获取页面
     * @param $params
     * @return array
     */
    public function getPageListByPaginate($params): array
    {
        $field = '*';
        $where = [];
        $order = 'order_id desc,page_id desc';
        $with = [
            'part' => function ($q) {
                $q->where('is_show', 1)->where('delete_time', 0);
            },
            'children' => function ($q) {
                $q->where('delete_time', 0);
            }
        ];
        if (array_key_exists('parent_id', $params) && $params['parent_id'] > 0) {
            $where[] = ['parent_id', '=', $params['parent_id']];
        } else {
            $where[] = function (Query $query) {
                $query->whereNull('parent_id')->whereOr('parent_id', 0);
            };
        }

        $paginate = [
            'page' => $params['page'] ?? 1,
            'limit' => $params['limit'] ?? 10,
        ];
        if (array_key_exists('all', $params)) {
            $paginate = [];
        }
//        $list = $this->cmsPageService->getPageList($pageIndex, $pageSize, $where, $field, $order, $with);
        $list = $this->getSubList(
            $this->cmsPageService, $field, $where,
            $order, $with, $paginate,
            'page_id', 'parent_id', 'children',
            false);
        return $list;
    }

    /**
     * 递归获取子集
     * @param BaseService $service 需要递归的Service
     * @param  $parent_id_name string parent_id的字段名
     * @param  $pk_name string 主键名称
     * @param  $children_name string 子集名称
     * @param  $field string 查询的字段
     * @param  $where array 筛选条件
     * @param  $order string 排序
     * @param  $with array 关联查询
     * @return array
     */
    private function getSubList(
        BaseService $service,
        string      $field,
        array       $where,
        string      $order,
        array       $with,
        array       $paginate = [],
        string      $pk_name = 'id',
        string      $parent_id_name = 'parent_id',
        string      $children_name = 'children',
        bool        $extendWhere = true
    ): array
    {
        if (count($paginate) > 0) {
            $list = $service->getPageList($paginate['page'], $paginate['limit'], $where, $field, $order, $with);
            $list = $list['list'];
        } else {
            $list = $service->getAll("*", $where, $order, $with);
        }
        $paginate = [];//只有首次传才有分页信息
        try {
            for ($i = 0; $i < count($list); $i++) {
                if (!$extendWhere) {
                    $where = [];
                }
                $where[$parent_id_name] = $list[$i][$pk_name];
                $list[$i]['isParent'] = count($list[$i][$children_name]) > 0;
                if (count($list[$i][$children_name]) > 0) {
                    $list[$i][$children_name] = $this->getSubList($service, $field, $where, $order, $with, $paginate, $pk_name, $parent_id_name);
                } else {
                    $list[$i][$children_name] = [];
                }
            }
            return $list;
        } catch (\Exception $exception) {
            throw $exception;
        }
    }

    /**
     * 获取产品分类
     * @param $params
     * @return array
     */
    public function getProductsCategoryList($params, $order = 'sort desc,id desc')
    {
        try {
            $field = '*';
            $parentId = 0;
            if (array_key_exists('parent_id', $params)) {
                $parentId = $params['parent_id'] ?? 0;
            }
            $where = [];
            $where['parent_id'] = $parentId;
            $with = [
                'children',
                "products" => function (Query $query) use ($params) {
                    if (array_key_exists('is_show', $params)) {
                        $query->where('is_show',1);
                    }
                },
                'relationPage',
            ];
            $paginate = [
                'page' => $params['page'] ?? 1,
                'limit' => $params['limit'] ?? 10,
            ];
            if (array_key_exists('all', $params)) {
                $paginate = [];
            }

            if (array_key_exists('is_show', $params)) {
                $where[] = ['is_show', '=', 1];
            }

            $list = $this->getSubList($this->productCategoryService, $field, $where, $order, $with, $paginate);
            $count = $this->productCategoryService->total($where);
            return ['list' => $list, 'count' => $count];
        } catch (\Exception $exception) {
            Log::debug("\n" . $exception->getMessage() .
                "\n" . $exception->getFile() . ":" . $exception->getLine()
            );
            return [];
        }
    }


    /**
     * 获取产品详情
     * @param $id
     * @return array
     */
    public function getProductCategoryDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $with = [
                'relationPage',
                'products',
                'children',
//                'extProducts',
//                'relationFields' => function (Query $query) {
//                    $query->order('sort desc');
//                }
            ];
            $res = $this->productCategoryService->getOne('*', $where, $with);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            Log::debug($e->getMessage() . "\n" . $e->getFile() . ":" . $e->getLine());
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 创建新的产品分类
     * @param $data
     * @return array
     */
    public function createNewProductCategory($data): array
    {
        try {
            $ret = $this->productCategoryService->insert($data);
            if ($ret) {
                buildRoute($data['name'], '/index/page/product', $data['rewrite_url'], ['id' => $ret], 'product');
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 更新产品分类
     * @param $id int 类型id
     * @param $data array 更新的数据
     * @return array
     */
    public function updateProductCategory(int $id, array $data): array
    {
        try {
            $where = [
                'id' => $id
            ];

            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->productCategoryService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['rewrite_url'];
            $title = $item['name'];
            if (array_key_exists('rewrite_url', $data)) {
                $buildUrl = $data['rewrite_url'];
            }
            if (array_key_exists('name', $data)) {
                $title = $data['name'];
            }
            updateRoute($title, '/index/page/product', $buildUrl, $removeUrl, ['id' => $id], 'product');


            $ret = $this->productCategoryService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (\Exception $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    /**
     * 删除产品分类
     * @param $id
     * @return array
     */
    public function deleteProductCategory($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $item = $this->productCategoryService->getOne("*", $where);
            removeRoute($item['rewrite_url'], 'product');
            $ret = $this->productCategoryService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    /**
     * 获取产品分类
     * @param $params
     * @return array
     */
    public function getProductsList($params)
    {
        try {
            $where = [];
            $field = '*';
            $this->getProFilter($where, $params);
            $order = 'sort desc,product_id desc';
            $paginate = [
                'page' => $params['page'] ?? 1,
                'limit' => $params['limit'] ?? 10,
            ];
            $with = [
                'productCategory',//产品分类
                'productExtFields' => function ($query) use ($params) {
                    $query->order('sort desc');
                },// 自定义字段
                'productContents'
            ];
            if (array_key_exists('all', $params)) {
                return $this->productService->getAll($field, $where, $order, $with);
            } else {
                return $this->productService->getPageList($paginate['page'], $paginate['limit'], $where, $field, $order, $with);
            }
        } catch (\Exception $exception) {
            logError($exception);
        }
    }


    /**
     * 获取产品详情
     * @param $id
     * @return array
     */
    public function getProductDetail($id): array
    {
        try {
            $where = [
                'product_id' => $id
            ];
            $with = [
                'productCategory',
                'productPhotos',//图片
                'productFiles',//文件
                'productApplication',//Application
                'productExtCat' => function (Query $query) {
                    $query->where('level', '=', 3);
                },// 拓展分类
                'productExtFields' => function ($query) {
                    $query->order('sort desc');
                }, // 自定义字段
                'productContents'
            ];
            $res = $this->productService->getOne('*', $where, $with);
            return $res;
        } catch (ValidateException $e) {
            Log::debug($e->getMessage() . "\n" . $e->getFile() . ":" . $e->getLine());
            return [];
        }
    }

    /**
     * 创建新的产品分类
     * @param $data
     * @return array
     */
    public function createNewProduct($data): array
    {
        try {
            $ret = $this->productService->insert($data);
            if ($ret) {
                buildRoute($data['name'], '/index/page/productDetail', $data['rewrite_url'], ['id' => $ret], 'product');
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 更新产品分类
     * @param $id int 类型id
     * @param $data array 更新的数据
     * @return array
     */
    public function updateProduct(int $id, array $data): array
    {
        try {
            $where = [
                'product_id' => $id
            ];
            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->productService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['rewrite_url'];
            $title = $item['name'];
            if (array_key_exists('rewrite_url', $data)) {
                $buildUrl = $data['rewrite_url'];
            }
            if (array_key_exists('name', $data)) {
                $title = $data['name'];
            }
            updateRoute($title, '/index/page/productDetail', $buildUrl, $removeUrl, ['id' => $id], 'product');


            $ret = $this->productService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage() . '\n' . $e->getFile() . ':' . $e->getLine());
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    /**
     * 删除产品分类
     * @param $id
     * @return array
     */
    public function deleteProduct($id): array
    {
        try {
            $where = [
                'product_id' => $id
            ];
            $item = $this->productService->getOne("*", $where);
            removeRoute($item['rewrite_url'], 'product');

            $ret = $this->productService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 添加图片集合
     * @param $data
     * @return array
     */
    public function createNewPhotos($data): array
    {
        try {
            $ret = $this->photosService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 创建新的产品资源
     * @param $data
     * @return array
     */
    public function createNewProductsFiles($data): array
    {
        try {
            $ret = $this->productsFilesService->insert($data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 移除指定的资源文件
     * @param $id
     * @return array
     */
    public function deleteProductsFiles($id)
    {
        try {
            $where = [
                'id' => $id
            ];
            $ret = $this->productsFilesService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage() . '\n' . $e->getFile() . ":" . $e->getLine());
            return $this->responseInfo(false, $e->getMessage());
        }

    }

    /**
     * 获取主程序的菜单页面
     * @param $action string 操作方法
     * @param $requestUrl string 请求的地址
     * @param $navId mixed navId
     * @return array
     */
    public function getIndexMenuList($action = null, $requestUrl = null, &$navId = null): array
    {
        $items = $this->getNavigateList(['isshow' => 1]);
        $menuList = [];
        for ($i = 0; $i < count($items); $i++) {
            if ($items[$i]['isshow']) {
                $menuList[] = $items[$i];
            }
        }

        // 获取页面片段进行渲染
        for ($i = 0; $i < count($menuList); $i++) {
            $menuList[$i]['active'] = $menuList[$i]['en_name'] == $action;

            // 如果不是锚链接的导航，应该让子页面的路由展现到导航上
            $children = $menuList[$i]['children'];
            // todo 根据场景生成指定路由
            if ($menuList[$i]['en_name'] == pageType['product']['name']) { //产品列表
                $productCatList = $this->getProductsCategoryList(['all' => 1])['list'];
                for ($k = 0; $k < count($productCatList); $k++) {
                    $urlParams = [
                        'id' => $productCatList[$k]['id'],
                    ];
                    $childrenUrl = paramsBuilder($urlParams);

                    $childrenItem['url'] = $childrenUrl;
                    if ($menuList[$i]['url'] . $childrenUrl == $requestUrl && $navId) {
                        $navId = $menuList[$i]['id'];
                    }
                    $childrenItem['type'] = 1;
                    $childrenItem['name'] = $productCatList[$k]['name'];
                    $childrenItem['children'] = $productCatList[$k]['children'];
                    $childrenItem['products'] = $productCatList[$k]['products'];
                    $childrenItem['main_url'] = $menuList[$i]['url'];
                    $childrenItem['isshow'] = $productCatList[$k]['is_show'];
                    $childrenItem['opennew'] = false;
                    $childrenItem['rewrite_url'] = $productCatList[$k]['rewrite_url'];
                    $childrenItem['id'] = $productCatList[$k]['id'];
                    $children[] = $childrenItem;
                }
            }

            $menuList[$i]['children'] = $children;
        }
        return $menuList;
    }

    /**
     * 根据导航创建页面
     * @return array
     */
    public function createPageByNavigate()
    {
        $navigate = $this->getNavigateList();
        $pagesData = [];
        for ($i = 0; $i < count($navigate); $i++) {
            if (
                $navigate[$i]['isshow'] &&
                $navigate[$i]['en_name'] != pageType['product']['name'] &&
                !$navigate[$i]['relationPage']
            ) {
                $pagesData[] = [
                    'nav_id' => $navigate[$i]['id'],
                    'title' => $navigate[$i]['name'],
                    'urlrewriter' => $navigate[$i]['writeurl'],
                    'url' => $navigate[$i]['url'],
                    'pagetitle' => $navigate[$i]['name'],
                    'pagekeywords' => $navigate[$i]['name'],
                    'pagedesc' => $navigate[$i]['name'],
                    'is_show' => 1,
                    'order_id' => 0
                ];
            }
        }
        $result = $this->cmsPageService->insertAll($pagesData);

        return $this->responseInfo($result > 0, $result > 0 ? 'SUCCESS' : 'FAILURE');
    }


    /**
     * 更新产品文件
     * @param $id
     * @param array $data
     * @return array
     */
    public function updateProductsFiles($id, array $data): array
    {
        $where = [
            'id' => $id
        ];
        $ret = $this->productsFilesService->update($where, $data);
        if ($ret) {
            return $this->responseInfo(true, 'SUCCESS');
        } else {
            return $this->responseInfo(false, 'FAILURE');
        }
    }

    /**
     * 案例分类列表
     * @param $params
     * @return array
     */
    public function getCaseCategoryList($params)
    {
        $field = '*';
        $where = [];
        $order = 'sort desc,id desc';
        $withs = ['cases'];
        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        if (array_key_exists('cat_ids', $params) && $params['cat_ids']) {
            $where[] = function (Query $query) use ($params) {
                $query->where('id', 'in', $params['cat_ids']);
            };
        }
        if (array_key_exists('is_show', $params) && $params['is_show']) {
            $where[] = function (Query $query) use ($params) {
                $query->where('is_show', '=', $params['is_show']);
            };
        }
        $result = $this->caseCategoryService->getPageList($pageIndex, $pageSize, $where, $field, $order, $withs);
        if (array_key_exists('all', $params)) {
            $result = $this->caseCategoryService->getAll($field, $where, $order, $withs);
        }
        return $result;
    }

    /**
     * 案例分类列表
     * @param $params
     * @return array
     */
    public function getCaseList($params)
    {
        $field = '*';
        $where = [];
        if (array_key_exists('cat_id', $params) && $params['cat_id']) {
            $where['cat_id'] = $params['cat_id'];
        }
        $order = 'sort desc,id desc';
        $withs = ['caseCategory'];
        $pageIndex = $params['page'] ?? 1;
        $pageSize = $params['limit'] ?? 10;
        $result = $this->caseService->getPageList($pageIndex, $pageSize, $where, $field, $order, $withs);
        if (array_key_exists('all', $params)) {
            $result = $this->caseService->getAll($field, $where, $order, $withs);
        }

        return $result;
    }

    /**
     * 添加案例分类
     * @param $data
     * @return array
     */
    public function createNewCaseCategory($data): array
    {
        try {
            $ret = $this->caseCategoryService->insert($data);
            buildRoute($data['name'], '/index/page/solutionlist', $data['rewrite_url'], ['id' => $ret], 'solution');

            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }


    /**
     * 添加案例
     * @param $data
     * @return array
     */
    public function createNewCase($data): array
    {
        try {
            $ret = $this->caseService->insert($data);
            if (isset($data['rewrite_url'])) {
                buildRoute($data['name'], '/index/page/casesinfo', $data['rewrite_url'], ['id' => $ret], 'cases');
            }
//            buildRoute($data['name'], '/index/page/cases', $data['urlrewriter'], ['id' => $ret]);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 更新案例分类
     * @param $id
     * @param $data
     * @return array
     */
    public function updateCaseCategory($id, $data): array
    {
        try {
            $where = [
                'id' => $id
            ];

            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->caseCategoryService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['rewrite_url'];
            $title = $item['name'];
            if (array_key_exists('rewrite_url', $data)) {
                $buildUrl = $data['rewrite_url'];
            }
            if (array_key_exists('name', $data)) {
                $title = $data['name'];
            }
            updateRoute($title, '/index/page/solutionlist', $buildUrl, $removeUrl, ['id' => $id], 'solution');

            $ret = $this->caseCategoryService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 更新案例
     * @param $id
     * @param $data
     * @return array
     */
    public function updateCase($id, $data): array
    {
        try {
            $where = [
                'id' => $id
            ];

            // 判断如果修改了自定义路由则 先删除路由再添加路由
            $item = $this->caseService->getOne("*", $where);
            $removeUrl = $buildUrl = $item['rewrite_url'];
            $title = $item['name'];
            if (array_key_exists('rewrite_url', $data)) {
                $buildUrl = $data['rewrite_url'];
            }
            if (array_key_exists('name', $data)) {
                $title = $data['name'];
            }
            updateRoute($title, '/index/page/casesinfo', $buildUrl, $removeUrl, ['id' => $id], 'cases');

            $ret = $this->caseService->update($where, $data);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 案例分类详情
     * @param $id
     * @return array
     */
    public function getCaseCategoryDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $withs = ['cases'];
            $res = $this->caseCategoryService->getOne('*', $where, $withs);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 案例详情
     * @param $id
     * @return array
     */
    public function getCaseDetail($id): array
    {
        try {
            $where = [
                'id' => $id
            ];
            $withs = ['caseCategory'];
            $res = $this->caseService->getOne('*', $where, $withs);
            if ($res) {
                return $this->responseInfo(true, 'SUCCESS', $res);
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 删除案例分类
     * @param $id
     * @return array
     */
    public function deleteCaseCategory($id): array
    {
        try {
            $where = [
                'id' => $id
            ];

            $item = $this->caseService->getOne("*", $where);
            removeRoute($item['rewrite_url'], 'solution');

            $ret = $this->caseCategoryService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 删除案例
     * @param $id
     * @return array
     */
    public function deleteCase($id): array
    {
        try {
            $where = [
                'id' => $id
            ];

            $item = $this->caseService->getOne("*", $where);
            removeRoute($item['rewrite_url'], 'solution');


            $ret = $this->caseService->softDel($where);
            if ($ret) {
                return $this->responseInfo(true, 'SUCCESS');
            } else {
                return $this->responseInfo(false, 'FAILURE');
            }
        } catch (ValidateException $e) {
            return $this->responseInfo(false, $e->getMessage());
        }
    }

    /**
     * 获取根的产品分类
     * @param $cat_id
     * @return mixed|void
     */
    public function getRootProductCatDetail($cat_id)
    {
        $proCat = $this->productCategoryService->getOne("id,parent_id", ['id' => $cat_id]);
        if ($proCat['parent_id'] == 0) {
            return $proCat['id'];
        } else {
            return $this->getRootProductCatDetail($proCat['parent_id']);
        }
    }


    /**
     * 分页查询拓展分类下的产品
     * @param $params
     * @return mixed
     */
    public function getProByRelListByCatId($params)
    {
        $where = [];
        if (array_key_exists('cat_id', $params)) {
            $where[] = ['cat_id', '=', $params['cat_id']];
        }
        $field = "*";
        $order = 'id desc';
        if (array_key_exists('all', $params)) {
            $result = $this->productsExtCatRelationsService->getAll($field, $where, $order);
        } else {
            $pageIndex = $params['page'] ?? 1;
            $pageSize = $params['limit'] ?? 10;
            $result = $this->productsExtCatRelationsService->getPageList($pageIndex, $pageSize, $where, $field, $order);
        }
        return $result;
    }


    /**
     * 获取产品数量
     * @param $params
     * @return int 获取产品数量
     */
    public function getProductsCount($params)
    {
        $where = [];
        $this->getProFilter($where, $params);
        return $this->productService->total($where);
    }

    /**
     * 统一处理产品筛选条件
     * @param $where
     * @param $params
     * @return void
     */
    private function getProFilter(&$where, $params)
    {
        if (array_key_exists('cate_id', $params) && $params['cate_id']) {
            $where['cate_id'] = $params['cate_id'];
        }
        if (array_key_exists('cat_id', $params) && $params['cat_id']) {
            $where['cate_id'] = $params['cat_id'];
        }

        if (count($params) > 0) {
            $where[] = function (Query $query) use ($params) {
                $query->where(true);

                if (array_key_exists('ids', $params) && $params['ids']) {
                    $query->whereIn('product_id', $params['ids']);
                }
                if (array_key_exists('is_show', $params) && $params['is_show']) {
                    $query->where('is_show', $params['is_show']);
                }

                if (array_key_exists('is_hot', $params) && $params['is_hot']) {
                    $query->where('is_hot', $params['is_hot']);
                }

                if (array_key_exists('keywords', $params) && $params['keywords']) {
                    $keywords = $params['keywords'];
                    if (gettype($keywords) === 'array') {
                        for ($i = 0; $i < count($keywords); $i++) {
                            $query->where('name', 'like', '%' . $keywords[$i] . '%');
                        }
                    } else {
                        $query->where('name', 'like', '%' . $keywords . '%');
                    }
                }
            };
        }
    }

    /**
     * 分页查询案例列表
     * @param $pageIndex
     * @param $pageSize
     */
    public function getCasesListByPages($pageIndex = 1, $pageSize = 10, $cat = 1, $condition = null, $search = null)
    {
        try {
            $where = [
                'cat_id' => $cat
            ];
            if ($cat == null && $cat == 0) {
                unset($where['cat_id']);
            }
            if ($search) {
                $keywords = $search['keywords'] ?? null;
                if ($keywords) {
                    $where[] = function ($query) use ($keywords) {
                        $query->whereLike('name', '%' . $keywords . '%');
                    };
                }
            }
            if ($condition) {
                if (array_key_exists('is_show', $condition)) {
                    $where[] = function ($query) use ($condition) {
                        $query->where('is_show', $condition['is_show']);
                    };
                }
                if (array_key_exists('cat_ids', $condition)) {
                    $where[] = function ($query) use ($condition) {
                        $query->where('cat_id', 'in', $condition['cat_ids']);
                    };
                }
            }
            $fields = "*";
            $order = 'create_time desc';
            $withs = ['caseCategory'];
            return $this->caseService->getPageList($pageIndex, $pageSize, $where, $fields, $order, $withs);
        } catch (\Exception $exception) {
            Log::debug($exception->getMessage());
            Log::debug($exception->getFile() . ":" . $exception->getLine());
            return [];
        }
    }

    /**
     * 分页查询案例列表
     * @param $pageIndex
     * @param $pageSize
     */
    public function getCasesSearchList($condition, $search = null)
    {
        try {
            if ($search) {
                /* $keywords = $search['keywords'] ?? null;
                 if ($keywords) {
                     $where[] = function ($query) use ($keywords) {
                         $query->whereLike('name', '%' . $keywords . '%');
                     };
                 }*/
                if (array_key_exists('keywords', $search)) {
                    $keywords = $search['keywords'];
                    if (gettype($keywords) === 'array') {
                        $where[] = function (Query $query) use ($keywords) {
                            for ($i = 0; $i < count($keywords); $i++) {
                                $query->whereOr('name', 'like', '%' . $keywords[$i] . '%');
                            }
                        };
                    } else {
                        $where[] = function ($query) use ($keywords) {
                            $query->whereLike('name', '%' . $keywords . '%');
                        };
                    }
                }
            }
            if ($condition) {
                if (array_key_exists('is_show', $condition)) {
                    $where[] = function ($query) use ($condition) {
                        $query->where('is_show', $condition['is_show']);
                    };
                }
            }
            $fields = "*";
            $order = 'create_time desc';
            $withs = ['caseCategory'];
            return $this->caseService->getAll($fields, $where, $order, $withs);
        } catch (\Exception $exception) {
            Log::debug($exception->getMessage());
            Log::debug($exception->getFile() . ":" . $exception->getLine());
            return [];
        }
    }

    /**
     * 获取上下一条案例
     * @param $id
     * @return array
     */
    public function getCaseForPreAndNextByCat($id, $catId): array
    {
        $prevWhere = [
            ['id', '<', $id],
            ['cat_id', '=', $catId],
        ];
        $nextWhere = [
            ['id', '>', $id],
            ['cat_id', '=', $catId],
        ];
        $prev = $this->caseService->getOne("*", $prevWhere);
        $next = $this->caseService->getOne("*", $nextWhere);
        return [
            'prev' => $prev,
            'next' => $next
        ];
    }
}
